<?php

class ImportVideoFromWinscp{

	protected $winscp_store_path   = '/data/pms/pdes/video/scp/';
	protected $folder_type_catchup = 20;
	protected $importer_user_id    = 'avsupport';
	protected $file_format         = array(
		'numVideoFiles',
		'breakpoints',
		'publish_datetime',
		'expire_datetime',
		'country_allow_list',
		'country_deny_list',
		'first_time_onair',
		'free_flag',
		'subscription_publish_datetime',
		'subscription_expire_datetime',
		'subscription_country_allow_list',
		'subscription_country_deny_list'
	);

    private $endline = 6 ; // index start 0

	############################ BEGIN Check function list ##############################
	/**
	 * return array for path checking
	 * @return Array
	 */
	public function getFileRule(){
	    $regular   = '#^'.$this->winscp_store_path.'([^/]+)/([^/]+)/([^/]+)/(\d+)/\1_\4_(\d+)\.txt$#';
	    $functions = array('checkProgrammePath', 'checkFolderTypePath', 'checkFolderName', 'checkEpisodeAirNo', 'checkFolderId');
		$item_keys = array('programme_info',     'folder_type_id',      '', 'episode_info',      'folder_id');
		return  array('regular'=>$regular,'functions'=>$functions,'item_keys'=>$item_keys);
	}
	public function checkFileName($file){
		$parts = $this->getFileRule();
		try{
			$result   = array();
			$regular  = $parts['regular'];
			$callback = $parts['functions'];
			$itemkeys = $parts['item_keys'];

			$match = preg_match_all($regular,$file,$out);
			if(!$match) throw new Exception('File name format error.');

			array_shift($out);
			foreach($out as $i=>$m){
				if(isset($callback[$i]) && $callback[$i]){
					if(isset($itemkeys[$i]) && $itemkeys[$i]){
						$result[$itemkeys[$i]] = $this->$callback[$i]($m[0]);
					}else{
						$this->$callback[$i]($m[0]); // only checking
					}
				}else{
					if(isset($itemkeys[$i]) && $itemkeys[$i]){
						$result[$itemkeys[$i]] = $m[0];
					}
				}
			}
			return $result;
		}catch(Exception $e){
			print_r($e);
			echo "\nFile name error.\n\tFile:[$file]\n\tMessage:".$e->getMessage()."\n";
			return false;
		}
	}
	public function checkProgrammePath($programme_path){
		$programme = new programme();
		if(!($programme_id = $programme->checkPath($programme_path))){
			throw new Exception("Programme path '$programme_path' not exists in database.");
		}
		$this->programme_id = $programme_id;
		return array('id'=>$programme_id,'path'=>$programme_path);
	}
	public function checkFolderName($folder_name){
		if(!preg_match("/^[\w _\-\.']+$/",$folder_name)){
			throw new Exception('Folder name should be Alphanumeric.');
		}
	}
	public function checkEpisodeAirNo($air_episode_no){
		$episode = new episode();
		if(!preg_match('/^\d+$/',$air_episode_no)){
			throw new Exception("Episode on_air_episode_no must be numeric.");
		}
		return array('id'=>$episode->getEpisodeID($this->programme_id,$air_episode_no),'air_no'=>$air_episode_no);
	}
	public function checkFolderTypePath($folder_path){
		$folder_type = new folder_type();
		if(!($folder_type_id = $folder_type->checkPath($folder_path))){
			throw new Exception("Folder folder_type_path not exists in database.");
		}
		$this->folder_type_id = $folder_type_id;
		$this->folder_path    = $folder_path;
		return $folder_type_id;
	}
	public function checkDataTime($publish_date,$expire_date){
		$regular = '/^\d{4}-\d{2}-\d{2}( ([01][0-9]|2[0-3])(:[0-5][0-9]){0,2})?$/';
		if(!preg_match($regular,$publish_date,$o1))  throw new Exception("[$publish_date] is not date");
		if(!preg_match($regular,$expire_date,$o2))   throw new Exception("[$expire_date] is not date");

		if(empty($o1[1])) $publish_date.=' 00:00:00';
		if(empty($o2[1])) $expire_date .=' 00:00:00';

		list($y,$m,$d) = explode('-',substr($publish_date,0,10));
		list($h,$i,$s) = explode(':',substr($publish_date.':00:00',11));
		if(!checkdate($m,$d,$y) || $y<2000 || $y>3000) throw new Exception("[$publish_date] is not date");
		$publish_time  = mktime($h,$i,$s,$m,$d,$y);

		list($y,$m,$d) = explode('-',substr($expire_date,0,10));
		list($h,$i,$s) = explode(':',substr($expire_date.':00:00',11));
		if(!checkdate($m,$d,$y) || $y<2000 || $y>3000) throw new Exception("[$expire_date] is not date");
		$expire_time   = mktime($h,$i,$s,$m,$d,$y);

		if(!$publish_time)              throw new Exception("[$publish_date] is not date");
		if(!$expire_time)               throw new Exception("[$expire_date] is not date");
		if($expire_time<=$publish_time) throw new Exception("'publish_datetime':[$publish_date] must be earlier than 'expire_datetime':[$expire_date]");
		return array(
			date('Y-m-d H:i:s',$publish_time),
			date('Y-m-d H:i:s',$expire_time)
		);
	}
	public function checkCountryList($allow,$deny){
		$allow_is_all = (strcasecmp($allow, 'All') == 0);
		$deny_is_all  = (strcasecmp($deny,  'All') == 0);

		if( ($allow_is_all && $deny_is_all) || (!$allow_is_all && !$deny_is_all) )
		{
			throw new Exception("The 'country_allow_list':[$allow] and 'country_deny_list':[$deny] value must be have a 'ALL' and only one is 'ALL'");
		}

		return array(
			$this->checkCountryExists($allow),
			$this->checkCountryExists($deny)
		);
	}
	public function checkCountryExists($country){
		if(strcasecmp($country,'NONE')==0 || $country == '') return '';
		if(strcasecmp($country,'ALL')==0)                    return 'ALL';

		$country_obj = new country;

		$checked_list = array();
		if(!$country_obj->checkGaoCountryList($country,$checked_list)){
			$import = explode(',',$country);
			throw new Exception("The 'country_list':[". implode(",",array_diff($import,$checked_list)) ."] not in database");
		}
		return implode(',',$checked_list);
	}
	public function checkFolderId($folder_id){
		$folder = new folder();
		if(($folder_info = $folder->get($folder_id))){
			if($folder_info->folder_type_id != $this->folder_type_id){
				throw new Exception("Folder[$folder_id] type[{$folder_info->folder_type_id}] unmatch folder path[{$this->folder_path}]");
			}
			return $folder_id;
		}
		throw new Exception("Folder id not exists in database.");
	}
	############################ Check function list END ##############################


	public function check(){
		exec('find ' . $this->winscp_store_path. ' -name "*.txt"',$files);

		$result = array();
		$failed = array();
		foreach($files as $file){
			$file_info = $this->checkFileName($file);
			#var_dump($file_info);
			if($file_info === false){
				$failed[] = $file;
				continue;
			}

			if(!$file_info['episode_info']['id'] && $file_info['episode_info']['air_no'] != '0'){
				$file_info['episode_info']['id'] = -1;
			}

			$programme = new programme();
			$programme_info = $programme->get($file_info['programme_info']['id']);

			$lines = file($file);
			$total_lines = count($lines);
			if($total_lines < $this->endline+1)
			{
				echo "File:[$file] format error!\n",print_r($lines,1);
				echo "Lines too few, lines must be equal to 7 or 11.\n\n";
				$failed[] = $file;
				continue;
			}elseif($total_lines> $this->endline+1){
                /*
				if($total_lines<11){
					echo "File:[$file] format error!\n",print_r($lines,1);
					echo "Lines must be equal to 6 or 11.\n\n";
					$failed[] = $file;
					continue;
                }else{
                 */
					if(empty($programme_info->premium_flag)){
						echo "File:[$file] format error!\n",print_r($lines,1);
						echo "Programme[{$file_info['programme_info']['id']}] premium_flag is 0, Not allow append subscription information.\n\n";
						$failed[] = $file;
						continue;
					}
				//}
			}

			#echo ','.$programme_info->folders.','  ,':',  ','.$file_info['folder_id'].',',"\n";
			if(strpos(','.$programme_info->folders.','  ,  ','.$file_info['folder_id'].',') === false){
				echo "File:[$file] format error!\n",print_r($lines,1);
				echo "Folder id[{$file_info['folder_id']}] not in programme[{$file_info['programme_info']['id']}].\n\n";
				$failed[] = $file;
				continue;
			}

			$all_not_null = true;
			foreach ($lines as $k => & $line) 
			{
				$line = trim($line);
				if( strlen($line)==0 )
				{
					$all_not_null = false;
					echo "File:[$file] format error!\n",print_r($lines,1);
					echo 'Line '. ($k+1) ." should not be empty\n\n";
					break;
				}
			}
			if(!$all_not_null){
				$failed[] = $file;
				continue;
			}

			if(!is_numeric($lines[0]))
			{
				echo "File:[$file] format error!\n",print_r($lines,1);
				echo "Line 1: '{$this->file_format[0]}' value is not numeric\n\n";
				$failed[] = $file;
				continue;
			}

			$directory = dirname($file);
			$video_files = glob( "$directory/{$file_info['episode_info']['air_no']}_*.mp4" );
			$image_files = glob( "$directory/{$file_info['episode_info']['air_no']}.jpg");
			if(empty($image_files) || count($video_files) != $lines[0])
			{
				echo "File:[$file] format error!\n",print_r($lines,1);
				echo "Video({$file_info['episode_info']['air_no']}_*.mp4) files total number not equal 'numVideoFiles' or no Image({$file_info['episode_info']['air_no']}.jpg) file\n\n";
				$failed[] = $file;
				continue;
			}

			# check image
			$if_data = CommonUtils::GetVideoInformation($image_files[0]);
			if(empty($if_data['General']['Format']) || $if_data['General']['Format']!='JPEG'){
				echo "File : '". $image_files[0] ."' not a JPEG file!\n";
				$failed[] = $file;
				continue;
			}

			# check video 
			$all_files_right = true;
			$video_info      = array();
			$video_duration=0;//added by Albie Lu on 2011-11-08
			foreach($video_files as $vf){
				$vf_data = CommonUtils::GetVideoInformation($vf);
				if(
					empty($vf_data['General']['Format'])
					|| $vf_data['General']['Format']!='MPEG-4'
					|| mime_content_type($vf) != 'video/mp4'
				){
					$all_files_right = false;
					echo "File : '". $vf ."' not a MPEG-4 file!\n";
					break;
				}
				if(empty($video_info)){
					$video_info['width']    = $vf_data['Video']['Width'];
					$video_info['height']   = $vf_data['Video']['Height'];
					$video_info['dispsize'] = $vf_data['Video']['DisplayAspectRatio/String'];
				}
				if($video_info['width'] != $vf_data['Video']['Width'] || $video_info['height'] != $vf_data['Video']['Height']){
					$all_files_right = false;
					echo "Path : '". dirname($vf) ."', All the MPGE-4 file size must be consistent!\n";
					break;
				}
				$video_duration += floor($vf_data['Video']['Duration']/1000);//added by Albie Lu on 2011-11-08
			}
			if(!$all_files_right){
				$failed[] = $file;
				continue;
			}
			
			$export_list = array();			
			if($video_info['dispsize'] == '16/9'){
				$export_list[] = 'mp4_hq';
				$export_list[] = 'mp4_900k';
				$export_list[] = 'mp4_mq';
				$export_list[] = 'mp4_lq';
//                                $export_list[] = 'iphone_lq';

			} else {
				$export_list[] = 'mp4_4/3:hq';
				//$export_list[] = 'mp4_4/3:mq';
				//$export_list[] = 'mp4_4/3:lq';
//                                $export_list[] = 'iphone_lq';

			}
			$exports = implode(",", $export_list);

			try{
				if(!preg_match('/^\d+(,\d+)*$/',$lines[1])){
					throw new Exception("Breakpoints format error, the format should be: ^[0-9]+(,[0-9]+)*$");
				}
				$video_date    = $this->checkDataTime($lines[2],$lines[3]);
				$video_country = $this->checkCountryList($lines[4],$lines[5]);

				if($total_lines > $this->endline+1){
                    $sub_data = $ppv_data = array();
                    $free_flag = '';

					$line_8 = 7;
					$line_9 = 8;
					$line_10 = 9;
					$line_11 = 10;
					$line_12 = 11;
					$line_13 = 12;
					$line_14 = 13;

					if (!empty($lines[$line_8])) {
                    	if ('SUBSCRIPTION:' === strtoupper($lines[$line_8])) { // Text file format 3 
							$free_flag = $this->__checkFreeFlag($lines[$line_9]);
                    	    $sub_data = $this->checkDataTime($lines[$line_10], $lines[$line_11]);

                    	    if(isset($lines[$line_12]) && 'PPV:' === strtoupper($lines[$line_12])) { // Text file format 2
                    	        $ppv_data = $this->checkDataTime($lines[$line_13],$lines[$line_14]);
                    	    } elseif(isset($lines[$line_12]) && 'PPV:' !== strtoupper($lines[$line_12])) {
                    	        throw new Exception('Format error, line 12 '.$lines[$line_12].' does not mean that ppv: ');
                    	    }
                    	} else if('PPV:' === strtoupper($lines[$line_8])) { // Text file format 5 
                    	    $ppv_data = $this->checkDataTime($lines[$line_9],$lines[$line_10]);

                    	    if(isset($lines[$line_11]) && 'SUBSCRIPTION:' === strtoupper($lines[$line_11])) { // Text file format 4 
								$free_flag = $this->__checkFreeFlag($lines[$line_12]);
                    	        $sub_data = $this->checkDataTime($lines[$line_13],$lines[$line_14]);
                    	    } elseif(isset($lines[$line_11]) && 'SUBSCRIPTION:' !== strtoupper($lines[$line_11])) {
                    	        throw new Exception('Format error, line 11 '.$line[$line_11].' does not mean that subscription: ');
                    	    }
                    	} else {
                    	    throw new Exception('Format error, line 8 '.$lines[$line_8].' does not mean that ppv: or subscription:');
                    	}
					}
                }
			} catch(Exception $e) {
				echo "File:[$file] format error!\n",print_r($lines,1);
				echo $e->getMessage();
				$failed[] = $file;
				continue;
			}

			$result[$file] = array(
				'programme_id'      => $file_info['programme_info']['id'],
				'episode_id'        => $file_info['episode_info']['id'],
				'programme_path'    => $file_info['programme_info']['path'],
				'on_air_episode_no' => $file_info['episode_info']['air_no'],
				'folder_id'			=> $file_info['folder_id'],
				'video_files'       => $video_files,
				'image_files'       => $image_files,
				'file_data'=>array(
					'exports'            => $exports,
					'numVideoFiles'      => (int) $lines[0],
					'breakpoints'        => $lines[1],
					'publish_datetime'   => $video_date[0],//$lines[2],
					'expire_datetime'    => $video_date[1],//lines[3],
					'country_allow_list' => $video_country[0],//lines[4],
					'country_deny_list'  => $video_country[1],//lines[5]
					'first_time_onair'   => $lines[$this->endline],//lines[6]
					'premium_flag'       => $programme_info->premium_flag,//for bug:7603 #added by Albie Lu on 2011-10-28
					'video_duration'     =>	$video_duration,//added by Albie Lu on 2011-11-08
				)
			);

			if ($total_lines> $this->endline+1) {
                if(empty($sub_data)) {
                    $result[$file]['file_data']['subscription'] = array();
                } else {
                    $result[$file]['file_data']['subscription'] = array(
                        'publish_datetime'   => $sub_data[0],
                        'expire_datetime'    => $sub_data[1] ,
                        'free_flag'          => $free_flag,
                    );
                }

                if(empty($ppv_data)) {
                    $result[$file]['file_data']['ppv'] = array();
                } else {
                    $result[$file]['file_data']['ppv'] = array(
                        'publish_datetime'   => $ppv_data[0] ,
                        'expire_datetime'    => $ppv_data[1] ,
                    );
                }
            }

			//for bug:7603  #modified by Albie Lu on 2011-10-28
			if(empty($ppv_data) && empty($sub_data) && $programme_info->premium_flag==1){
				$result[$file]['file_data']['subscription'] = array(
					'publish_datetime'   => $result[$file]['file_data']['publish_datetime'],
					'expire_datetime'    => $result[$file]['file_data']['expire_datetime'],
					'free_flag'          => 0,
				);
			}
        }

		return $result;
	}

	public function import($data){
		$finish  = array();
		$mail_to = CommonUtils::getAdminMail('winscp');
		foreach($data as $file=>$row){
			$video_id = $this->insertIntoTable($row['programme_id'], $row['episode_id'], $row['on_air_episode_no'], 
											  $row['folder_id'], $row['file_data']);
			if($video_id){
				$finish[] = $file;
				$this->generationJsonFile($video_id,$row['video_files'],$row['image_files'],$row['file_data']);

				$basename = $row['programme_path'].'_'.$row['on_air_episode_no'];
				$this->_deleteFiles(array($file));
				if (empty($row['episode_id'])) {
					$row['episode_id'] = episode::getEpisodeID($row['programme_id'], $row['on_air_episode_no']);
				}
				
				mail($mail_to, "$basename is imported, Video ID = $video_id", print_r($row,1));
			}
		}
		#$this->_renameFiles($finish,'checked');
		return $finish;
	}

	public function generationJsonFile($video_id,$video_files,$image_files,$data){
		$content = array(
			'video_id'           => $video_id,
			'exports'            => $data['exports'],
			'numVideoFiles'      => $data['numVideoFiles'],
			'breakpoints'        => $data['breakpoints'],
			'publish_datetime'   => $data['publish_datetime'],   
			'expire_datetime'    => $data['expire_datetime'],    
			'country_allow_list' => $data['country_allow_list'],
			'country_deny_list'  => $data['country_deny_list']  
		);
		$video_store_dir = AC::VIDEO_STORE_PATH.$video_id;

		file_exists($video_store_dir.'/part/') || mkdir($video_store_dir.'/part/',0755,true);

		$json_file_name = $video_store_dir . '/json';
		
		//copy video files
		foreach($video_files as $index=>$v_f){
			$index_name = sprintf("%012d",$index);
			copy($v_f, $video_store_dir.'/part/'.$index_name.'.mp4');
		}

		//copy image file
		copy($image_files[0], $video_store_dir.'/part/image.jpg');

		file_put_contents($json_file_name, json_encode($content));
	}

	public function insertIntoTable($programme_id, & $episode_id, $on_air_episode_no, $folder_id,$data){
		Model::$dbo['w']->beginTransaction();
		try{
            /*
             * create episode if not exists for bug 778
             */
			$new_episode_id = $episode_id;
			$new_video_id   = '';
			$mix_title      = '';
			$now_time       = date('Y-m-d H:i:s');

			# change_log
			$change_logs = array();

            if ($episode_id == -1)
            {
				$episode = new episode;
				$episode->programme_id = $programme_id;
				$episode->onair_episode_no = $on_air_episode_no;
				$episode->first_time_onair = $data['first_time_onair'];
				$episode->publish_datetime = $data['publish_datetime'];
				$episode->expire_datetime = $data['expire_datetime'];
				$episode->highlighted_cast_roles = CommonUtils::get_highlight_role("episode");
				$episode->available_tag_types = CommonUtils::get_allow_tags("episode");
				$episode->folders = CommonUtils::init_folder('episode');
				$episode->status = AC::STATUS_NEW;
				$episode->created_at = date('Y-m-d H:i:s');
				$episode->created_by = 'system';
				$episode->modified_at = date('Y-m-d H:i:s');
				$episode->modified_by = 'system';

				$new_episode_id = $episode->insert();
				$episode_id = $new_episode_id;

                $sql = "INSERT INTO `episode-language`(`episode_id`, `language_id`, `title`) VALUES(:a, :b, :c)";
				$langs = array(language::getLanguageID(AC::LANGUAGE_ZH),language::getLanguageID(AC::LANGUAGE_EN));
				
				# change_log
				$change_logs[] = array('type' => 'episode','keys' => array('id'=>$episode_id),'episode' => array($episode_id));
				foreach($langs as $l){
					Model::updateBySql($sql, array(':a'=>$episode_id, ':b'=>$l, ':c'=>''));
					$change_logs[] = array(
						'type' => 'episode-language',
						'keys' => array('episode_id'=>$episode_id,'language_id'=>$l),
						'episode' => array($episode_id)
					);
				}
			}elseif($episode_id){
				# if video exists then return video.id
				$find_video_id = "
					SELECT item_id AS video_id FROM `folder_item` 
					WHERE 
						folder_id=$folder_id AND 
						item_id IN(
							SELECT video_id FROM `episode-video` WHERE episode_id=$episode_id
						)";
				$old_video = Model::selectBySql($find_video_id);
				if(count($old_video)>=1){
					echo "Notice:\n\tFolder [$folder_id] inside already exists episode [$episode_id] videos!\n";
					echo "\tThe new video will replace the original video:{$old_video[0]['video_id']}!";
					$new_video_id = $old_video[0]['video_id'];
				}else{
					$episode  = new episode();
					$episode_data = $episode->getDetails($episode_id);
					$zh_language_id = language::getLanguageID(AC::LANGUAGE_ZH);
					$en_language_id = language::getLanguageID(AC::LANGUAGE_EN);
					$mix_title  = $episode_data->episode_language[$zh_language_id]->title . ' ';
					$mix_title .= $episode_data->episode_language[$en_language_id]->title;
				}
				Model::updateBySql('UPDATE episode SET status=?,modified_at=now() WHERE id=?',array(AC::STATUS_NEW,$episode_id));
				# change_log
				$change_logs[] = array('type' => 'episode','keys' => array('id'=>$episode_id),'episode' => array($episode_id));
			}

            
			$programme = Model::$dbo['r']->findInstance('programme',$programme_id);


			if($new_video_id){
				# Update Video Info
				Model::updateBySql('UPDATE video SET modified_at=now() WHERE id=:id',array(':id'=>$new_video_id));
				$vo_id = $new_video_id;
				# change_log
				$change_logs[] = array('type' => 'video','keys' => array('id'=>$vo_id),'programme_id' => $programme_id);


				/* -----------begin    
				 * change the time of this video's chapter when the video is changed  
				 * #added by Albie Lu on 2011-11-07
				 * */

				//get the totle duration of the video
				$video_duration = $data['video_duration'];
				$video_id = $vo_id;
				$uploader = $this->importer_user_id;

				/* if the in_time or out_time of chapter is greater than the video duration,
				 * set them to the video duration.*/
				$sql = "select id,in_time,out_time from chapter where video_id='{$video_id}' and status=".AC::STATUS_NEW." and (in_time>'{$video_duration}' or out_time>'{$video_duration}')";
				$chapter_lists = Model::$dbo['r']->findBySql('chapter', $sql);	
				foreach ($chapter_lists as $chapter_one){
					$chapter_one->in_time = ($chapter_one->in_time > $video_duration) ? $video_duration : $chapter_one->in_time;
					$chapter_one->out_time = $video_duration;
					$chapter_one->modified_at = $now_time;
					$chapter_one->modified_by = $uploader;
					Model::$dbo['w']->save($chapter_one);
					//change_log
					change_log::updateOne(array(
						'type'=>'chapter',
						'keys'=>array('id'=>$chapter_one->id),
						'is_active'=>1,
						'is_publish'=> 0,
						'programme_id'=>$programme_id
					));
				}

				//if the max out_time of chapter < video duration,set this out_time to video duration  
				if(count($chapter_lists)==0){
					$sql_c = "select max(in_time) from chapter where video_id='{$video_id}' and status=".AC::STATUS_NEW;
					$sql = "select id,in_time,out_time from chapter where video_id='{$video_id}' and status=".AC::STATUS_NEW." and in_time=(".$sql_c.")";
					$chapter_lists = Model::$dbo['r']->findBySql('chapter', $sql);
					$n=0;
					foreach($chapter_lists as $chapter_one){
						if( $chapter_one->out_time<$video_duration ){
							if($n<0){
								$chapter_one->in_time = $video_duration;
							}
							$n--;
							$chapter_one ->out_time = $video_duration;
							$chapter_one->modified_at = $now_time;
							$chapter_one->modified_by = $uploader;
							Model::$dbo['w']->save($chapter_one);
							//change_log
							change_log::updateOne(array(
								'type'=>'chapter',
								'keys'=>array('id'=>$chapter_one->id),
								'is_active'=>1,
								'is_publish'=> 0,
								'programme_id'=>$programme_id
							));
						}
					}
				}
				//------------end

			}else{
				# insert record
				// Create Video Record
				$video_obj = new video();
				$video_obj->programme_id        = $programme_id;
				$video_obj->ii_id               = '';
				$video_obj->ii_status           = AC::IMAGE_STATUS_WAITING;
				$video_obj->thumbnail_url       = '';
				$video_obj->image_source_url    = '';
				$video_obj->vi_id               = '';
				$video_obj->vi_status           = AC::VIDEO_STATUS_QUEUE;
				$video_obj->video_params        = '';
				$video_obj->source_url          = '';
				$video_obj->other_videos        = '';
				//$video_obj->first_time_onair    = '';
				$video_obj->first_time_onair    = $data['first_time_onair'];
				$video_obj->highlighted_cast_roles= '';
				$video_obj->available_tag_types = '';
				$video_obj->casts               = '';
				$video_obj->tags                = '';
				$video_obj->folders             = '';
				$video_obj->country_allow_list  = $data['country_allow_list'];
				$video_obj->country_deny_list   = $data['country_deny_list'];
				$video_obj->publish_datetime    = $data['publish_datetime'];
				$video_obj->expire_datetime     = $data['expire_datetime'];
				$video_obj->copyright           = '';
				$video_obj->status              = AC::STATUS_NEW;
				$video_obj->mdes_status         = AC::STATUS_NEW;
				$video_obj->premium_flag        = 0; //for bug:7603     #modified by Albie Lu on 2011-10-28
				$video_obj->created_at          = $now_time;
				$video_obj->created_by          = $this->importer_user_id;
				$video_obj->modified_at         = $now_time;
				$video_obj->modified_by         = $this->importer_user_id;
				$vo_id = Model::$dbo['w']->save($video_obj);
				# change_log
				$change_logs[] = array('type' => 'video','keys' => array('id'=>$vo_id),'programme_id' => $programme_id);

				$deflang = language::getLanguageID(AC::DEFAULT_LANGUAGE);
				$vol = new video_language();
				$vol->video_id    = $vo_id;
				$vol->language_id = $deflang;
				$vol->title       = trim(str_replace("\n\t",' ',$mix_title));
				$vol->description = '';
				Model::$dbo['w']->save($vol);
				# change_log
				$change_logs[] = array(
					'type' => 'video-language',
					'keys' => array('video_id'=>$vo_id,'language_id'=>$deflang),
					'programme_id' => $programme_id
				);

				if($new_episode_id){
					// insert episode-video
					$sql = 'INSERT IGNORE INTO `episode-video`(`episode_id`,`video_id`) VALUES(:a,:b)';
					Model::updateBySql($sql,array(':a'=>$new_episode_id,':b'=>$vo_id));
					# change_log
					$change_logs[] = array(
						'type' => 'episode-video',
						'keys' => array('video_id'=>$vo_id,'episode_id'=>$new_episode_id),
						'programme_id' => $programme_id
					);
				}

				// insert folder_item
				$folder_item_obj = new folder_item();
				$max_rank   = $folder_item_obj->getMaxRank($folder_id);
				Model::updateBySql('insert into folder_item values(:fid,:item_id,:rank)',array(':fid'=>$folder_id,':item_id'=>$vo_id,':rank'=>$max_rank+1));
				Model::updateBySql('insert into `folder_item-language` values(:fid,:item_id,:lang,:title,:desc)',array(':fid'=>$folder_id,':item_id'=>$vo_id,':lang'=>$deflang,':title'=>$vol->title,':desc'=>$vol->description));
				# change_log
				$change_logs[] = array(
					'type' => 'folder',
					'keys' => array('id'=>$folder_id),
					'programme_id' => $programme_id
				);
				$change_logs[] = array(
					'type' => 'folder_item',
					'keys' => array('item_id'=>$vo_id,'folder_id'=>$folder_id),
					'programme_id' => $programme_id
				);
				$change_logs[] = array(
					'type' => 'folder_item-language',
					'keys' => array('item_id'=>$vo_id,'folder_id'=>$folder_id,'language_id'=>$deflang),
					'programme_id' => $programme_id
				);
			}

            $premium_sub = $premium_ppv = 0;
            if(!empty($data['subscription']) && $data['premium_flag']==1){//for bug:7603  #modified by Albie Lu on 2011-10-28
                $premium_sub = 1;
				$sv = new video_subscription();
				$old_sv = $sv->get($vo_id);
				if($old_sv) $sv = $old_sv;

				$sv->video_id           = $vo_id;
				$sv->publish_datetime   = $data['subscription']['publish_datetime'];
				$sv->expire_datetime    = $data['subscription']['expire_datetime'];
				$sv->country_allow_list = AC::DEFAULT_COUNTRY_ALLOW_LIST; 
				$sv->country_deny_list  = AC::DEFAULT_COUNTRY_DENY_LIST; 
				$sv->free_flag          = $data['subscription']['free_flag'];

				Model::$dbo['w']->save($sv);
				# change_log
				$change_logs[] = array(
					'type' => 'video_subscription',
					'keys' => array('video_id'=>$vo_id),
					'programme_id' => $programme_id
				);
			}
            if(!empty($data['ppv']) && $data['premium_flag']==1){//for bug:7603  #modified by Albie Lu on 2011-10-28
                $premium_ppv=1;
				$ppv = new video_ppv();
				$old_ppv = $ppv->get($vo_id);
				if($old_ppv) $ppv = $old_ppv;
				$ppv->video_id           = $vo_id;
				$ppv->publish_datetime   = $data['ppv']['publish_datetime'];
				$ppv->expire_datetime    = $data['ppv']['expire_datetime'];
				$ppv->country_allow_list = AC::DEFAULT_COUNTRY_ALLOW_LIST; 
				$ppv->country_deny_list  = AC::DEFAULT_COUNTRY_DENY_LIST; 
				Model::$dbo['w']->save($ppv);
				# change_log
				$change_logs[] = array(
					'type' => 'video_ppv',
					'keys' => array('video_id'=>$vo_id),
					'programme_id' => $programme_id
				);
			}
            $video_premium = new video_premium();
            $video_premium_old =  $video_premium->get($vo_id);
            if($video_premium_old) $video_premium = $video_premium_old;
            $video_premium->video_id = $vo_id;
            $video_premium->subscription_flag = $premium_sub;
            $video_premium->ppv_flag = $premium_ppv;
			Model::$dbo['w']->save($video_premium);
			# change_log
			$change_logs[] = array(
				'type' => 'video_premium',
				'keys' => array('video_id'=>$vo_id),
				'programme_id' => $programme_id
			);

            if($premium_sub || $premium_ppv)
            {
                $video = new video();
                $video = $video->get($vo_id);
                $video->premium_flag = 1;
			    Model::$dbo['w']->save($video);
            }

			array_walk($change_logs,'change_log::updateOne');

			Model::$dbo['w']->commit();
			return $vo_id;
		}
		catch(PDOException $e)
		{
			Model::$dbo['w']->rollBack();
			print_r($e);
			return false;
		}
	}
	
	private function _renameFiles(array $files,$new_file_name){
		foreach($files as $file){
			$dir = dirname($file);
			rename($file, $dir.'/'.$new_file_name);
		}
	}

	private function _deleteFiles(array $files){
		foreach($files as $file){
			$dir = dirname($file);
			$old_files = glob($dir.'/*');
			foreach($old_files as $pf){
				unlink($pf);
			}
			@rmdir($dir);
		}
		return true;
	}

	private function __checkFreeFlag($str)
	{
		$free_flag = strtoupper($str);

		switch ($free_flag) {
			case 'FREE':
				$free_flag = 1;
				break;
			case 'NON-FREE':
				$free_flag = 0;
				break;
			default:
				throw new Exception("The 'free_flag' line must be 'FREE' or 'NON-FREE'");
				break;
		}

		return $free_flag;
	}
}
?>
